<?php
/**
 * @Description: 直播管理
 * @Author: kzj
 * @datetime: 2023-02-24
 */
namespace App\Services\Teaching;

use App\Models\DictionaryItem;
use App\Models\FormInstance;
use App\Models\System\Term;
use App\Models\SystemTask;
use App\Models\Teaching\Live;
use App\Models\Teaching\TeachingSubject;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

/**
 * 直播管理 (服务)
 */
class LiveService
{
    /** @var \App\Repositories\Teaching\LiveRepository $liveRepository */
    private $liveRepository;

    public function __construct()
    {
        $this->liveRepository = app('liveRepository');
    }


    /**
     * @Description: 直播管理列表信息数据
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function getList($request)
    {
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;

        $name = '';
        $creator = '';
        $startTime = '';
        $endTime = '';
        $filters = [];
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $filters[] = ['data_version_id', '=', $request['search']['data_version_id']];
        }
        if (isset($request['search']['name'] )&& !empty($request['search']['name'])){
            $name = $request['search']['name'];
        }
        if (isset($request['search']['live_time'] )&& !empty($request['search']['live_time'])){
            $times = explode(' - ', $request['search']['live_time']);
            $startTime = $times[0];
            $endTime = $times[1];
        }
        if (isset($request['search']['subject_dic_id'] )&& !empty($request['search']['subject_dic_id'])){
            $filters[] = ['subject_dic_id', '=', $request['search']['subject_dic_id']];
        }
        if (isset($request['search']['grade_dic_id'] )&& !empty($request['search']['grade_dic_id'])){
            $filters[] = ['grade_dic_id', '=', $request['search']['grade_dic_id']];
        }
        if (isset($request['search']['creator'] )&& !empty($request['search']['creator'])){
            $creator = $request['search']['creator'];
        }
        if (isset($request['search']['status'] )&& !empty($request['search']['status'])){
            // $filters[] = ['status', '=',  $request['search']['status']];
        }

        $result = Live::where($filters)
            ->when($name, function($q) use($name) {
                $q->where('name', 'like', '%'.$name.'%');
            })
            ->when($startTime && $endTime, function($q) use($startTime, $endTime) {
                $q->where('start_time', '<=', $startTime)->where('end_time', '>=', $endTime);
            })
            ->when($creator, function($q) use($creator) {
                $q->whereHas('creator', function($query) use($creator) {
                    $query->where('nickname', 'like', '%'.$creator.'%');
                });
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){
                $q->where('creator_id', $request['user_id']);
            })
            ->whereDeleted(0)
            ->where('is_sub', 1)
            ->with('term', 'creator')
            ->orderBy('id', 'desc')
            ->paginate($limit, '*', 'page', $page)
            ->toArray();

        return $result;
    }

    /**
     * @Description: 直播管理添加
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function add($request)
    {
        if(empty($request)) {
            throw new \Exception('请选择数据');
        }

        $user = Auth::user();
        $request['creator_id'] = $user->id;
        
        if(isset($request['grade_dic_id']) && !empty($request['grade_dic_id'])) {
            $request['grade'] = DictionaryItem::whereId($request['grade_dic_id'])->first()->item_name;
        }
        if(isset($request['subject_dic_id']) && !empty($request['subject_dic_id'])) {
            $request['subject'] = DictionaryItem::whereId($request['subject_dic_id'])->first()->item_name;
        }
        if(isset($request['live_time']) && !empty($request['live_time'])) {
            $times = explode(' - ', $request['live_time']);
            $request['start_time'] = $times[0];
            $request['end_time'] = $times[1];
        }

        try{   
            DB::beginTransaction();
            
            $result = Live::create($request);

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }
            
        return $result;
    }


    /**
     * @Description: 直播管理单条数据
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function one($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }
        
        $result = Live::where('id', $request['id'])->with('creator', 'term')->first();
        
        return $result;
    }

    /**
     * @Description: 直播管理编辑
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function edit($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }
        
        if(isset($request['grade_dic_id']) && !empty($request['grade_dic_id'])) {
            $request['grade'] = DictionaryItem::whereId($request['grade_dic_id'])->first()->item_name;
        }
        if(isset($request['subject_dic_id']) && !empty($request['subject_dic_id'])) {
            $request['subject'] = DictionaryItem::whereId($request['subject_dic_id'])->first()->item_name;
        }
        if(isset($request['live_time']) && !empty($request['live_time'])) {
            $times = explode(' - ', $request['live_time']);
            $request['start_time'] = $times[0];
            $request['end_time'] = $times[1];
        }

        try{   
            DB::beginTransaction();
            
            $result = Live::whereId($request['id'])->update($request);

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }
            
        return $result;
    }


    /**
     * @Description: 直播管理删除
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function del($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }
        
        $result = Live::whereId($request['id'])->update(['deleted' => 1]);

        return $result;
    }

}